from gifpy_util import main
from moviepy.editor import *
import re
import json
import random
import uuid
with open('gifs.json','r',encoding='utf8') as gj:
    gifJson = json.load(gj)
with open('videos_ssyer.json','r',encoding='utf8') as vsj:
    videoJson = json.load(vsj)
with open('videos.json','r',encoding='utf8') as mj:
    movieJson = json.load(mj)

clip_list = [gifJson, videoJson, movieJson]

# 随机素材获取
def randomClips():
    return random.choice(random.choice(clip_list))


# 提取音轨
def getAudio(url):
    if url[-4:] == ".mp4":
        audio_clip = VideoFileClip(url)
    else:
        audio_clip = AudioClip(url)
    return audio_clip


# 根据时长获取素材信息list
def getVideoByDuration(duration):
    # 视频信息数组
    clip_data_list = []
    clip_list = []
    # 初始化开始时间
    video_start = 0
    while(video_start < duration):
        # 视频片段url(str)
        print(f"进度{video_start}/{duration}")
        clip_data = randomClips()
        clip_type = clip_data["type"]
        clip_url = clip_data["url"]
        # 片段文件
        if clip_type == "gif":
            clip = VideoFileClip(clip_url)
            clip_list.append(clip.set_start(video_start).set_pos(("center","center")))
            clip_data_list.append({
                'video_start': video_start,
                'clip_url': clip_url
            })
            video_start = video_start + clip.duration
        else:
            clip_duration = random.randint(5, 10)
            clip = VideoFileClip(clip_url)
            clip_start = random.randint(0, int(clip.duration) - clip_duration)
            clip_list.append(
                clip.subclip(clip_start, clip_start + clip_duration)
                .set_start(video_start)
                .set_pos(("center","center"))
            )
            clip_data_list.append({
                'video_start': video_start, 
                'clip_url': clip_url, 
            })
            video_start = video_start + clip_duration
    # 素材列表
    print(clip_data_list)
    return CompositeVideoClip(clip_list, size=(848, 480))


# 分段拼接(若视频长度超过300s,将进行分段)
def splicingEvery(audio_video):
    duration = audio_video.duration
    if duration > 300:
        audio_video1 = audio_video.subclip(0, duration / 2)
        splicingEvery(audio_video1)
        audio_video2 = audio_video.subclip(duration / 2, duration)
        splicingEvery(audio_video2)
    else:
        clip = getVideoByDuration(duration)
        writeVideo(clip.set_audio(audio_video.audio))



def writeVideo(clip, video_name = f"{uuid.uuid1()}.mp4"):
    clip.write_videofile(video_name)


# 根据音频地址提取音频
def getVideoByAudio(audio_url):
    splicingEvery(getAudio(audio_url))

def test(duration):
    clip = getVideoByDuration(duration)
    writeVideo(clip)


if __name__ == '__main__':
    # clip_list = gifJson
    test(100)
    # getVideoByAudio('E:/pybase/audio001.mp4')
    